package cn.enilu.flash.api.config.magic;


import cn.enilu.flash.security.JwtUtil;
import cn.enilu.flash.utils.HttpUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.model.JsonBean;
import org.ssssssss.magicapi.core.model.Options;
import org.ssssssss.script.MagicScriptContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 自定义请求拦截器，可实现鉴权
 * https://ssssssss.org/magic-api/pages/senior/interceptor/
 * @see RequestInterceptor
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class CustomRequestInterceptor implements RequestInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(CustomRequestInterceptor.class);
    /**
     * 接口请求之前
     * @param info	接口信息
     * @param context	脚本变量信息
     */
    @Override
    public Object preHandle(ApiInfo info, MagicScriptContext context, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //用户信息
        Long userId = JwtUtil.getUserId();

        // 如果指定了任何人都能访问，直接放行
        if ("true".equals(info.getOptionValue(Options.ANONYMOUS))) {
            return  null;
        }

        // 如果指定了必须登录，则需要登录
        Object loginRequire = info.getOptionValue(Options.REQUIRE_LOGIN);

        if ("true".equals(loginRequire) || loginRequire == null ) {
            if (userId == null) {
                return new JsonBean<>(401, "用户未登录");
            }
        }

        //有用户的情况下，进行权限检查
        if(!Objects.isNull(userId)) {
            context.set("sysUserId",userId);
            context.set("sysUserName",JwtUtil.getUsername());

//暂不验证权限
//            Boolean checkPermissionResult = false;
//
//            String permission = info.getOptionValue(Options.PERMISSION);
//            if (StringUtils.isNotBlank(permission)) {
//                String[] permissions = permission.split(";");
//                Collection<? extends GrantedAuthority> authorities = SecurityUtils.getCurrentUser().getAuthorities();
//                for(GrantedAuthority xx : authorities){
//                    xx.getAuthority();
//                }
//
//                List<String> elPermissions = SecurityUtils.getCurrentUser().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
//                checkPermissionResult = elPermissions.contains("admin") || Arrays.stream(permissions).anyMatch(elPermissions::contains);
//            }else
//            {
//                //不设置默认全部用户都能访问
//                checkPermissionResult = true;
//            }
//
//            if (checkPermissionResult) {
//                return null;
//            } else {
//                return new JsonBean<>(403, "用户权限不足");
//            }
        }

        return  null;


//        Object user = null; // = XXXUtils.getUser(request);
//        logger.info("{} 请求接口：{}", user, info.getName());
//        // 接口选项配置了需要登录
//        if ("true".equals(info.getOptionValue(Options.REQUIRE_LOGIN))) {
//            if (user == null) {
//                return new JsonBean<>(401, "用户未登录");
//            }
//        }
//        String role = info.getOptionValue(Options.ROLE);
//        if (StringUtils.isNotBlank(role)/* && user.hasRole(role)*/) {
//            return new JsonBean<>(403, "用户权限不足");
//        }
//        String permission = info.getOptionValue(Options.PERMISSION);
//        if (StringUtils.isNotBlank(permission)/* && user.hasPermission(permission)*/) {
//            return new JsonBean<>(403, "用户权限不足");
//        }
//        return null;
    }

    /**
     * 接口执行之后
     * @param info	接口信息
     * @param context	变量信息
     * @param value 即将要返回到页面的值
     */
    @Override
    public Object postHandle(ApiInfo info, MagicScriptContext context, Object value, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //logger.info("{} 执行完毕，返回结果:{}", info.getName(), null);
        return null;
    }


//    /**
//     * 初步检测Token
//     *
//     * @param request /
//     * @return /
//     */
//    private String resolveToken(HttpServletRequest request) {
//        String bearerToken = request.getHeader(properties.getHeader());
//        if (org.springframework.util.StringUtils.hasText(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) {
//            // 去掉令牌前缀
//            return bearerToken.replace(properties.getTokenStartWith(), "");
//        } else {
//            log.debug("非法Token：{}", bearerToken);
//        }
//        return null;
//    }
}
